/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
 //2 3 4 5 6 7 
class Solution {

public:
    int getLen(ListNode* head){
        
        int len=0;
        while(head){
            head=head->next;
            ++len;
        }
        return len;
    }
    TreeNode* buildTree(ListNode*& head,int left,int right){

        if(left>right){
            return nullptr;
        }
        int mid=(right+left+1)/2;
        TreeNode* root=new TreeNode();
        root->left=buildTree(head,left,mid-1);
        root->val=head->val;
        head=head->next;
        root->right=buildTree(head,mid+1,right);
 
        return root;
    }
    TreeNode* sortedListToBST(ListNode* head) {
        
        int len=getLen(head);
        TreeNode* nRet=buildTree(head,0,len-1);
        
        return nRet;
    }
};
